package com.fromfuture.xuhuidoc.cordova.plugin;

import android.Manifest;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by hp on 2017/6/19.
 */

public class PermissionAudioVideoPlugin extends CordovaPlugin{

    CallbackContext callbackContext_permission;
    private Dialog noticeDialog;
    final int MYRECRDD=1;
    Camera mCamera = null;
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        callbackContext_permission=callbackContext;
        Log.e("摄像头有木有：",""+hasCamera());
        if (hasCamera()) {
            if (ContextCompat.checkSelfPermission(cordova.getActivity(), Manifest.permission.CAMERA) ==
                    PackageManager.PERMISSION_GRANTED) {//相等，同时shouldShowRequestPermissionRationale此时为false；6.0以下，全部为相等并且为false；
                //用户已经授权，可以进行后续操作了

                if (Build.VERSION.SDK_INT >= 23) {//6.0以上不用判断用户是否拒绝了，
                    callbackContext_permission.success("permission_ok");
                } else {//关于6.0以下得做判断是否被拒绝
                    if (cameraIsCanUse()) {//true,权限已打开，不管直接跳
                        callbackContext_permission.success("permission_ok");
                    } else {//false，权限被关闭，防止崩盘，提示用户
//                        callbackContext_permission.success("permission_six_before_video_no");//手机
                        callbackContext_permission.success("permission_ok");//电视
                    }
                }

            } else {
                //需要申请权限
                ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
                //a：弹出框框点了不再提醒并拒绝，点了以后就是false；点了永远允许后也是false；
                boolean a = ActivityCompat.shouldShowRequestPermissionRationale(cordova.getActivity(),
                        Manifest.permission.CAMERA);
                // 此处的方法最好做成异步的，而不要阻塞住当前进程，当用户看到解释作出反应后，再次申请权限
                if (!a) {//不相等同时shouldShowRequestPermissionRationale为false，调用下部分
                    callbackContext_permission.success("permission_six_before_video_no");
                } else if (a) {//如果用户已按允许，请按左上角 退出 按钮，重新进入即可，6.0以上
                    callbackContext_permission.success("permission_six_before_video_ye_chongjin");
                }
            }
        }else {//没有摄像头，防止崩盘
            callbackContext_permission.success("no_find_camera");
        }
        return super.execute(action, args, callbackContext);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        Toast.makeText(cordova.getActivity(),"fdf:  ",Toast.LENGTH_LONG).show();
//        switch (requestCode) {
//            case MYRECRDD:
//                if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//                    // 获取权限成功。操作继续。
//                    callbackContext_permission.success("permission_ok11");
//                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
//                }
//                break;
//            default:
//                break;
//        }
//    }




    private void goMainager() {
        try {
            Intent intent = new Intent("com.xlsgrid.net.gzchis");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
            intent.setComponent(comp);
            cordova.getActivity().startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(cordova.getActivity(), "跳转失败"+e, Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }


    public boolean cameraIsCanUse() {//暴力解决
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.stopPreview();

                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }


    /**检查是否有摄像头
     */
    private static boolean checkCameraFacing(final int facing) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        final int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, info);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查设备是否有摄像头
     */
    public static boolean hasCamera() {
        return hasBackFacingCamera() || hasFrontFacingCamera();
    }

    /**
     * 检查设备是否有后置摄像头
     */
    public static boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    /**检查设备是否有前置摄像头
     */
    public static boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

}
